package safari.model.transaction;

import java.sql.SQLException;

import org.mybatis.spring.SqlSessionTemplate;

import safari.model.sell.SellBoardVO;
import safari.model.transaction.TradeHistoryVO;

public class TransactionServiceImpl implements TransactionService {
	private TransactionDao transactionDao;
	private SqlSessionTemplate sqlSessionTemplate;
	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate){
		this.sqlSessionTemplate=sqlSessionTemplate;
	}
	public TransactionServiceImpl(TransactionDao transactionDao){
		this.transactionDao=transactionDao;
	}
	
	@Override
	public void transaction(String buyerId, String sellerId, SellBoardVO svo)
			throws SQLException, SoldOutException {
		int price=svo.getProductPrice();
		int balance=transactionDao.selectBalance(buyerId);
		if(balance<price){
			throw new SoldOutException("잔여 포인트가 부족합니다.");
		}else if(svo.getSellStatus().equals("판매완료")){
			throw new SoldOutException("이미 판매된 상품입니다.");
		} else if(svo.getSellStatus().equals("판매중")){
		// 트랜잭션 시작
		transactionDao.updateBuyer(new TransactionVO(buyerId, price));
		transactionDao.updateSeller(new TransactionVO(sellerId, price));
		transactionDao.updateSellStatus("판매완료", svo.getSellNo());
		transactionDao.insertTradeHistory(new TradeHistoryVO(new SellBoardVO(svo.getSellNo()), buyerId, sellerId));
		}
	}

}
